package com.fingard.dsp.bank.directbank.icbc02.receiptpro;

import java.io.File;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptData;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptDataHelper;
import com.fingard.dsp.bank.directConfig.ReceiptProConfig;
import com.fingard.dsp.bank.directbank.icbc02.ICBC02ReceiptPro;
import com.fingard.dsp.bank.helpers.receipthelpers.DownReceiptFileHelper;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.dsp.bank.sepro.ReceiptPro;
import com.fingard.dsp.task.command.SyncReceipt;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;

public class ICBC02ReceiptProFtpHeadVersion extends ICBC02ReceiptPro {
	
	/**ftp方式，
1)	文件为PDF文件，文件名为: 账号+’_’+交易日期+‘_’+11位银行流水号.pdf
2)	每个pdf文件，生成对应的签名文件：账号+’_’+交易日期+‘_’+11位银行流水号.pdf.sign
3)	使用zip格式压缩文件，文件名为: 集团ID+’_’+系统日期（yyyyMMdd）+’_’+所有的zip包个数+’_’+序号（5位）+“.zip”,每200笔（pdf文件+签名文件）打成1个zip包。
4)	文件为T-1日的明细，如果明细过多，会分包发送，通过ZIP文件名中的序号来区分。

新增支持新格式：账号_日期_流水号_地区号#网点号#柜员号#主机交易流水号_生成的顺序号.pdf
*
*/
	@Override
	public RetAtsReceipt qryReceiptOneDay(ReceiptProConfig pConfig, ReqQryReceipt pReqReceipt, Date pOneDay) throws Exception {
		
    	String qryDay8 = Format.Date8Format.format(pOneDay);
		String saveDirPathTemp = pConfig.getSaveSubDir(pReqReceipt.reqHeader, pOneDay) + File.separator + qryDay8 + File.separator + ReceiptPro.getTransID();
		String chkDay = "_"+qryDay8+"_";
		//调用通用下载方法
		DownReceiptFileHelper downFileHelper = new DownReceiptFileHelper(this);
		downFileHelper.downAndUnZipFiles(saveDirPathTemp, chkDay);
		
		//调用提取pdf文件的方法
		getPdfFiles(pConfig, pReqReceipt, pOneDay, saveDirPathTemp);
		
		WriteBankLogLn("删除"+saveDirPathTemp);
        FileHelper.deleteRecursive(saveDirPathTemp);
        
		return null;

	}
	
	private void getPdfFiles(ReceiptProConfig pConfig, ReqQryReceipt pReqReceipt, Date pOneDay, String pReceiptDir){
		ReceiptDataHelper receiptHelper = null;//回单数据保存类，分区分表
		try{
        	receiptHelper = new ReceiptDataHelper(pReqReceipt.reqHeader.tenant, pOneDay);
        	File receiptDir = new File(pReceiptDir);
        	
        	int[] retVals = getPdfLoop(pConfig, pReqReceipt, pOneDay, receiptHelper, receiptDir);
        	//[0]总数 [1]新增 [2]已存在
            WriteBankLogLn("目录"+pReceiptDir+"\r\n遍历总数"+retVals[0]+"，新增"+retVals[1]+"条，已存在"+retVals[2]+"条");
            if(retVals[1]>0){
            	SyncReceipt.resetDelayCounter();
            }
        	
		}catch(Exception ex){
        	this.WriteBankLogLn(ex);
        }finally{
        	if(receiptHelper != null){
        		receiptHelper.close();
        	}
        }
	}
	
	/**下载的日期目录中提取该账号对应的html，再提取pdf
	 * @param pRelativeSaveDir 相对文件夹目录*/
	private int[] getPdfLoop(ReceiptProConfig pConfig, ReqQryReceipt pReqReceipt, Date pOneDay, ReceiptDataHelper pReceiptHelper, File pDir){
		int[] retVals = new int[3];
		retVals[0] = 0;//总pdf个数
		retVals[1] = 0;//新增
		retVals[2] = 0;//已存在
    	File[] files = pDir.listFiles();
    	for (File eachFile : files) {
    		try{
    			if(eachFile.isDirectory()){
        			int[] subVals = getPdfLoop(pConfig, pReqReceipt, pOneDay, pReceiptHelper, eachFile);
        			retVals[0] = retVals[0] + subVals[0];
        			retVals[1] = retVals[1] + subVals[1];
        			retVals[2] = retVals[2] + subVals[2];
        		}
    			
    			String eachName = eachFile.getName().toLowerCase();
                if (eachName.endsWith(".pdf")) {
                	retVals[0] = retVals[0] + 1;
                	//1202020209900311818_20191118_19322000001.PDF
                	String[] nameAndExt = StringHelper.splitFileNameAndExt(eachName);
                	String[] nameSplit = nameAndExt[0].split("_");
                	
                	String bkOwnAct = "";
                	String istNbr = "";
                	String receiptNo = "";
                	String busRef = "";
                	String busDate = "";
                	
                	if(nameSplit.length == 6){
                		//[0]账号_[1]日期_[2]流水号_[3]11位银行流水号_地区号#网点号#柜员号#主机交易流水号_生成的顺序号.pdf
                		bkOwnAct = nameSplit[0];
                		busDate = nameSplit[1];
                		istNbr = nameSplit[3]+nameSplit[1];
                		receiptNo = nameSplit[3];
                		busRef = nameSplit[2];
                	}else if(nameSplit.length == 5){
                		//0502121129200365115_[1]20200611_[2]20163000001_[3]0000#1210#00023#15033626_00001.pdf
                		bkOwnAct = nameSplit[0];
                		busDate = nameSplit[1];
                		istNbr = nameSplit[2]+nameSplit[1];
                		receiptNo = nameSplit[2];
                		if(nameSplit[3].contains("#")){
                			String[] spBySharp = nameSplit[3].split("#");
                			if(spBySharp.length==4){
                				busRef = spBySharp[3].trim();
                			}
                		}
                		if(StringHelper.isNullOrEmpty(busRef)){
                			busRef = nameSplit[2];
                		}
                	}else if(nameSplit.length == 3){
                		//账号_日期_11位银行流水号.pdf
                		bkOwnAct = nameSplit[0];
                		busDate = nameSplit[1];
                		istNbr = nameSplit[2]+nameSplit[1];
                		receiptNo = nameSplit[2];
                		busRef = nameSplit[2];
                	}else{
                		WriteBankLogLn("文件名"+eachName+"不符合预期格式");
                		continue;
                	}
                	
                	if(StringHelper.isAllZeroOrEmpty(busRef)){
                		busRef = receiptNo;
                	}
                	ReceiptData eachData = new ReceiptData();
                    eachData.istNbr = istNbr;
                    eachData.ownAct = bkOwnAct;
                    eachData.setBusDate(pOneDay);
                    
                  //重命名
                    String renameToPath = pConfig.getSaveSubDir(pReqReceipt.reqHeader, pOneDay) + File.separator + String.valueOf(eachData.busDate) + File.separator + eachData.ownAct;
                    FileHelper.mkdirsIfNotExists(renameToPath);
                    renameToPath += File.separator + eachFile.getName();
                    File destFile = new File(renameToPath);
                    
                    /*
                    //同时保存sign文件
                    String signFilePath = eachFile.getAbsolutePath()+".sign";
                    File signFile = new File(signFilePath);
                    if(signFile.exists()){
                    	String signRename = renameToPath+".sign";
                    	File signReFile = new File(signRename);
                    	if(!signReFile.exists()){
                    		signFile.renameTo(signReFile);
                    	}
                    }*/
                    
                    boolean reResult;
                    if(destFile.exists()){
                    	reResult = true;
                    }else{
                    	reResult = eachFile.renameTo(destFile);
                    }
                    if(reResult){
                    	eachData.localFile = StringHelper.getRelativePath(destFile.getAbsolutePath(), pConfig.localSaveMainDir);
                    	eachData.srcFile = eachFile.getName();
                        eachData.busRef = busRef;
                        eachData.receiptNo = receiptNo;
                        eachData.bank = "102";
                        eachData.srcSys = "ICBC02";
                        
                        if(!String.valueOf(eachData.busDate).equals(busDate)){
                        	WriteBankLogLn("提取的日期"+busDate+"不符合预期"+String.valueOf(eachData.busDate)+"，回单文件名:" + eachFile.getName());
                        	eachData.downInfo = busDate+"-文件中提取的日期";
                        }
                        
                        eachData.downState = "2";
                        eachData.downTime = new Date();
                        
                        int inRe = pReceiptHelper.insertIfNotExistByReceiptNo(eachData, true);
                        if(inRe>0){
                        	retVals[1] = retVals[1] + 1;
                        }else if(inRe == 0){
                        	retVals[2] = retVals[2] + 1;
                        }
                        WriteBankLogLn(eachData.receiptNo+"写入数据库，影响行数："+inRe);
                    }else{
                    	WriteBankLogLn(eachData.receiptNo+"重命名失败：\r\n"+eachFile.getAbsolutePath()+"\r\n重命名为：\r\n"+renameToPath);
                    }
                }
                
    		}catch(Exception ex){
    			WriteBankLogLn(ex, eachFile.getAbsolutePath());
    		}
    	}
    	return retVals;
	}

}
